package com.aaa.zs.filter;

import com.aaa.zs.service.UserService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @fileName.LoginFilter
 * @description:
 * @author:zwl
 * @createTime:2020/11/13 15:17
 * @version:1.0.0
 */
@Component
public class LoginFilter extends ZuulFilter {
    @Autowired
    private UserService userService;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("进入了字符过滤器。。。");
        //使用zuul包中提供请求上下文类获取请求上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request =currentContext.getRequest();
        //获取response对象
        HttpServletResponse response = currentContext.getResponse();
        //获取请求地址
        String requestURL=request.getRequestURI();
        //获取token
        String accessToken = request.getParameter("accessToken");
        //判断是否为登录请求  判断是否带有token，再判断token是否正确
        if (requestURL.contains("/sso/ulactController/userLogin")||
                (!StringUtils.isEmpty(accessToken))&&userService.checkToken(accessToken)){
            //放行
            currentContext.setSendZuulResponse(true);
        }else {
            //拦截
            currentContext.setSendZuulResponse(false);
            try {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("您还没有登录，请先登录再访问！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
